package com.link.play.fit.ai.utils

import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.pushWorker.MealsPushWorker
import com.link.play.fit.ai.utils.AppX.applicationContext
import com.link.play.fit.ai.utils.TimeUtils.pmToLocalTime
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.temporal.ChronoUnit
import java.util.concurrent.TimeUnit

object DailyScheduleManager {

     fun scheduleTask(workName: String, targetTime: String, id: String) {
        // 计算初始延迟时间
        val initialDelay = calculateInitialDelay(pmToLocalTime(targetTime))
         val newWork = OneTimeWorkRequestBuilder<MealsPushWorker>()
             .setInitialDelay(initialDelay, TimeUnit.MILLISECONDS).setInputData(
                 workDataOf(
                     "TIME" to targetTime,
                     "workName" to workName,
                     "id" to id,
                 )
             )
             .build()

         WorkManager.getInstance(applicationContext)
             .enqueueUniqueWork(
                 workName,
                 ExistingWorkPolicy.REPLACE,
                 newWork
             )
    }



    private fun calculateInitialDelay(targetTime: LocalTime): Long {
        val now = LocalDateTime.now()
        var scheduledTime = now.with(targetTime)

        // 如果当前时间已过目标时间，则调度到明天
        if (scheduledTime.isBefore(now)) {
            scheduledTime = scheduledTime.plusDays(1)
        }

        return ChronoUnit.MILLIS.between(now, scheduledTime)
    }
}